
<template>
  <div class="dialogBox">
    <el-input :style="{ width: width }" :size="size" v-model="selectionLabel" :placeholder="placeholder" suffix-icon="el-icon-search" :disabled="openDisabled" :readonly="true" @focus="dialogTableVisible = true">
    </el-input>
    <el-dialog title="人员选择" append-to-body :visible.sync="dialogTableVisible" width="1000px" custom-class="dLog">
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="5" :xs="24">
          <div class="head-container">
            <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" default-expand-all @node-click="handleNodeClick" />
          </div>
        </el-col>
        <el-col :span="19" :xs="24">
          <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="small" style="width: 240px">
                <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker :editable="false" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <!-- <lb-table
            v-show="multiple == false || multiple == 'false'"
            v-loading="loading"
            ref="lbTable"
            highlight-current-row
            pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[2,5, 10, 20, 30, 100]"
            :pager-count="5"
            :current-page.sync="queryParams.pageNum"
            :total="queryParams.total"
            :page-size="queryParams.pageSize"
            @size-change="handleSizeChange"
            :data="tableData"
            @p-current-change="handleCurrentChange($event)"
            @current-change="selectionChange"
          >
          </lb-table> -->
          <!-- <div style="margin-top: 20px">
            <el-button @click="toggleSelection([tableData.data[1], tableData.data[0]])">切换第二、第三行的选中状态</el-button>
          </div> -->
          <Lbtable v-if="multiple == false || multiple == 'false'" v-loading="loading" ref="lbTable" highlight-current-row pagination cell-class-name="li_table" max-height="400" background layout="total, sizes, prev, pager, next, jumper" :page-sizes="[20]" :current-page.sync="queryParams.pageNum" :total="queryParams.total" :page-size="queryParams.pageSize" @size-change="handleSizeChange" :column="tableData.column" :data="tableData.data" @p-current-change="handleCurrentChange($event)" @current-change="selectionChange">
          </Lbtable>
          <Lbtable v-if="multiple == true || multiple == 'true'" v-loading="loading" ref="multipleTable" highlight-current-row pagination background layout="total, sizes, prev, pager, next, jumper" :page-sizes="[20]" :current-page.sync="queryParams.pageNum" :total="queryParams.total" :page-size="queryParams.pageSize" @size-change="handleSizeChange" :column="tableData.column" :data="tableData.data" @p-current-change="handleCurrentChange($event)" @selection-change="selectionChange($event)" @select="select" @select-all="selectAll">
          </Lbtable>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit" :disabled="disabled">确 定</el-button>
        <el-button @click="dialogTableVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Lbtable from "@/components/lb-table/lb-table";
import { listUser } from "@/api/system/user";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  props: {
    url: String,
    arr: Array | Object,
    multiple: {
      type: Boolean | String,
      default: false,
    },
    echoValue: String,
    openDisabled: {
      type: Boolean | String,
      default: false,
    },
    placeholder: {
      type: String,
      default: "请选择部门人员",
    },
    value: {
      type: String,
      default: "userId",
    },
    label: {
      type: String,
      default: "nickName",
    },
    width: {
      type: String,
      default: "100%",
    },
    size: {
      type: String,
      default: "",
    },
  },
  components: { Treeselect, Lbtable },
  watch: {
    echoValue: function (newVal, oldVal) {
      this.selectionLabel = this.echoValue;
    },
    dialogTableVisible: function (newVal, oldVal) {
      if (this.dialogTableVisible == true) {
        this.modal = true;
        this.queryParams.pageNum = 1;
        this.reset();
        this.getList();
        this.getTreeselect();
        this.getDicts("sys_normal_disable").then((response) => {
          this.statusOptions = response.data;
        });
        // this.currentRow = [];
        if (this.multiple == true || this.multiple == "true") {
          this.selectList = [];
        } else {
          this.selectList = {};
        }
        this.disabled = true;
      }
    },
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
    // 是否禁用
    selectList(val) {
      try {
        if (this.multiple == true || this.multiple == "true") {
          if (this.selectList.length == 0) {
            this.disabled = true;
          } else {
            this.disabled = false;
          }
        } else {
          if (JSON.stringify(this.selectList) == "{}") {
            this.disabled = true;
          } else {
            this.disabled = false;
          }
        }
      } catch (e) {
        console.log(e);
        // 错误处理代码片段
      }
    },
  },
  created() {
    this.selectionLabel = this.echoValue;
  },
  data() {
    return {
      // 是否禁用
      disabled: false,
      // 是否加载
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 弹窗是否显示
      dialogTableVisible: false,
      // 表格数据
      tableData: {
        column: [],
        data: [],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      // 状态数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      currentRow: [],

      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      //选择后处理的对象
      selection: {
        value: null,
        label: null,
        options: null,
      },
      selectionLabel: "",
      selectList: null, //选择数据
    };
  },
  methods: {
    //选择
    selectionChange(val) {
      if (val instanceof Array == true) {
        for (let item of val) {
          item.pageNum = this.queryParams.pageNum;
        }
        this.selectList.push(...val);
        this.selectList = this.deWeightThree(this.selectList);
      } else {
        if (val != null) {
          this.selectList = val;
        }
      }
    },
    select(selection, row) {
      let temp = 0;
      if (selection instanceof Array == true) {
        if (this.selectList.length > 0) {
          for (let index in this.selectList) {
            if (this.selectList[index].userId == row.userId) {
              this.selectList.splice(index, 1);
              temp++;
            }
          }
          if (temp == 0) {
            row.pageNum = this.queryParams.pageNum;
            this.selectList.push(row);
          }
        }
      }
    },
    selectAll(selection) {
      if (selection.length == 0) {
        this.selectList = this.selectList.filter(
          (item) => item.pageNum !== this.queryParams.pageNum
        );
      }
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      if (this.multiple == true || this.multiple == "true") {
        this.tableData.column = [
          {
            type: "selection",
          },
          { label: "用户编号", prop: "userId", align: "center" },
          // { label: "用户名称", prop: "userName", align: "center" },
          { label: "用户名称", prop: "nickName", align: "center" },
          { label: "手机号码", prop: "phonenumber", align: "center" },
        ];
      } else {
        this.tableData.column = [
          { label: "用户编号", prop: "userId", align: "center" },
          // { label: "用户名称", prop: "userName", align: "center" },
          { label: "用户名称", prop: "nickName", align: "center" },
          { label: "手机号码", prop: "phonenumber", align: "center" },
        ];
      }
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.tableData.data = response.rows;
          this.queryParams.total = response.total;
          // for (let items of this.tableData.data) {
          //   for (let item of Object.keys(items)) {
          //     if (
          //       items[item] == null ||
          //       items[item] == "" ||
          //       items[item] == undefined
          //     ) {
          //       items[item] = "--";
          //     }
          //   }
          // }
          this.loading = false;
          if (this.multiple == true || this.multiple == "true") {
            let hasIdArr = [];
            let list = [];
            this.selectList.forEach((item) => hasIdArr.push(item.userId));
            this.tableData.data.forEach((item) => {
              hasIdArr.includes(item.userId) && list.push(item);
            });
            clearTimeout(settimeout);
            var settimeout = setTimeout(() => {
              list.forEach((item) => {
                this.$refs.multipleTable.toggleRowSelection(item);
              });
            }, 100);
          } else {
            this.selectList = {};
          }
          // console.log(this.selectList)
        }
      );
    },
    // toggleSelection(rows) {
    //   rows.forEach((row) => {
    //     // console.log(row);
    //     this.$refs.multipleTable.toggleRowSelection(row);
    //   });
    // },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    deWeightThree(arr) {
      // let map = new Map();
      // for (let item of arr) {
      //   if (!map.has(item.userId)) {
      //     map.set(item.userId, item);
      //   }
      // }
      // return [...map.values()];
      let arr1 = []; //存id
      let newArr = []; //存新数组
      for (let i in arr) {
        if (arr1.indexOf(arr[i].userId) == -1) {
          arr1.push(arr[i].userId);
          newArr.push(arr[i]);
        }
      }
      return newArr;
    },
    //改变页码
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    //改变一页的数量
    handleSizeChange(val) {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = val;
      this.getList();
    },
    submit(e) {
      console.log(this.selectList);
      let value = this.value;
      let label = this.label;
      if (this.multiple == true || this.multiple == "true") {
        this.selection.options = new Array();
        this.selection.value = new Array();
        this.selection.label = new Array();
        for (let j of this.selectList) {
          let obj = new Object();
          obj.value = j[value];
          obj.label = j[label];
          this.selection.options.push(obj);
          this.selection.value.push(j[value]);
          this.selection.label.push(j[label]);
        }
        let selection = JSON.parse(JSON.stringify(this.selection));
        selection.label = selection.label.toString();
        selection.value = selection.value.toString();
        this.selectionLabel = selection.label;
        this.$emit("dialogChange", selection);
        this.dialogTableVisible = false;
      }
      if (this.multiple == false || this.multiple == "false") {
        this.selection.options = new Object();
        this.selection.value = new Object();
        this.selection.label = new Object();
        this.selection.options = this.selectList;
        this.selection.value = this.selectList[value];
        this.selection.label = this.selectList[label];
        this.selectionLabel = this.selection.label;
        this.$emit("dialogChange", this.selection);
        this.dialogTableVisible = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100%;
  .item {
    width: 31%;
    height: 48%;
    float: left;
    margin: 0 0 1% 1.7%;
    background: rgba(9, 59, 118, 0.9);
    box-shadow: 0 0 7px #ccffff;
  }
}
</style>
<style lang="scss">
.dialogBox {
  .el-table {
    max-height: 50vh !important;
    padding: 0px;
    margin-top: 13px;
    background: rgb(15 47 86 / 70%) !important;
    overflow: auto;
  }
  .el-table__body tr.current-row > td {
    // background: #115395 !important;
    background: none !important;
    // background-color: #19204e !important;
  }
  .el-form {
    padding: 10px 12px;
    background: rgb(15 47 86 / 70%) !important;
  }
  .el-form-item {
    margin-bottom: 3px !important;
  }
  .el-radio__inner,
  .el-checkbox__inner {
    border: 1px solid #1890ff;
  }
  .el-radio__input.is-checked,
  .el-checkbox__input.is-checked {
    .el-radio__inner,
    .el-checkbox__inner {
      background: #1890ff;
    }
  }
}
</style>

